package com.cloudz.iptv.utils;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * @File Name: com.cloudz.iptv.utils
 * @Author: YJ //作者及
 * @Date: 2018-12-17 10:18//完成日期
 * @Description: // 网络辅助类
 * @Version: v0.0.1 // 版本信息
 * @Function List: // 主要函数及其功能
 * @Others: // 其它内容的说明
 * @History: // 历史修改记录
 */
public class RetrofitUtils
{
    private static RetrofitUtils retrofitUtils;

    private final OkHttpClient okHttpClient;

    /**
     * 双重检验锁
     *
     * @return
     */
    public static RetrofitUtils getInstance()
    {
        if (retrofitUtils == null)
        {
            synchronized (RetrofitUtils.class)
            {
                if (retrofitUtils == null)
                {
                    retrofitUtils = new RetrofitUtils();
                }
            }
        }
        return retrofitUtils;
    }

    private RetrofitUtils()
    {
        okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(InterceptorUtils.LogInterceptor())//设置日志拦截器
                .addInterceptor(InterceptorUtils.HeaderInterceptor())//头部拦截器
                .writeTimeout(5, TimeUnit.SECONDS)//写入超时时间
                .readTimeout(5, TimeUnit.SECONDS)//读取超时时间
                .connectTimeout(5, TimeUnit.SECONDS)//超时时间
                .build();
    }

    public <T> T createApi(String baseUrl, Class<T> cls)
    {
        Retrofit retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(baseUrl)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                //设置数据解析器
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        return retrofit.create(cls);
    }
}
